<script setup lang="ts">
import { watchEffect,reactive,onMounted,ref,watch } from 'vue'
import { useMainStore } from '@/store/index'
import { useMainLogin } from '@/store/user'
import {
  Search,
  Refresh,
  EditPen,
  TrendCharts,
  FolderOpened,
  CloseBold,
  RefreshLeft
} from '@element-plus/icons-vue'
import * as mars3d from "mars3d"
import {getDefectList,isPointInBetweenStations,getUserList} from '@/api/road/index'
import { ElLoading, ElMessage, ElMessageBox } from 'element-plus'
import downloade from "@/api/downloade"

const Cesium = mars3d.Cesium
const store = useMainStore()
const user = useMainLogin()
const queryParams = ref({
  pageNum: 1,
  pageSize: 20,
  total: 0,
  roadName: '',
  stakeNumber: '',
  defectLevel:'',
  repairStatus:'',
  userName: '',
  userId: user.userId,
})
const showAll = ref(false)

const handleQuery = () => {
  getList()
}
const tabShow = ref(false)
const tableData = ref([])

const dataNameList = ['一般', '轻', '中', '重'];
const repairStatusList = ['无需维修','待维修','已派单', '维修完成'];

const getRowStyle = () => {
  return {
    background: 'transparent',
    color: 'white',
    borderBottomColor: 'rgba(255, 255, 255, 0.1)' // 可选边框
  };
}

const resetQuery = async () => {
  queryParams.value.pageNum = 1;
  queryParams.value.pageSize = 20;
  queryParams.value.total = 0;
  queryParams.value.roadName = '';
  queryParams.value.stakeNumber = '';
  queryParams.value.defectLevel = '';
  queryParams.value.repairStatus = '';
  queryParams.value.userName = '';
  if (user.roles.includes('superadmin')) {
    queryParams.value.userId = ''
  }else{
    queryParams.value.userId = user.userId
  }
  await getList()
}

const closeTab = () => {
  // 如果当前有编辑状态，先结束编辑
  if (store.graphicDefectId) {
    store.graphicDefectOperate = '结束修改'
  }
  store.closeAllForms()
  window.graphicDefect.clearDrawing()
}

const startDraw = () => {
  tabShow.value = true
  window.startDraw()

  // 添加键盘监听事件
  document.addEventListener('keydown', handleKeyDown)
}

// 处理键盘事件
const handleKeyDown = (e: KeyboardEvent) => {
  if (e.ctrlKey && (e.key === 'z' || e.key === 'Z')) {
    e.preventDefault()
    stepBack()
  } else if (e.ctrlKey && (e.key === 's' || e.key === 'S')) {
    e.preventDefault()
    endDraw()
  }
}

const parseMultipolygon = (multipolygonStr) => {
  // 1. 提取最内层的坐标字符串
  const coordinatesMatch = multipolygonStr.match(/\(\(\(([^)]+)\)\)\)/);
  if (!coordinatesMatch) return [];
  
  // 2. 分割坐标点并处理
  const points = coordinatesMatch[1].split(',')
    .map(pointStr => {
      // 移除可能存在的空格并分割经纬度
      const [lng, lat] = pointStr.trim().split(/\s+/);
      
      // 转换为浮点数并返回数组
      return [parseFloat(lng), parseFloat(lat)];
    });

  return points;
}

const handleSizeChange = (val: number) => {
  getList()
}
const handleCurrentChange = (val: number) => {
  getList()
}

const getList = async () => {
  window.graphicDefect.clear()
  await getDefectList(queryParams.value).then(res=>{
    if(res.code === 200) {
      tableData.value = res.rows
      queryParams.value.total = res.total
      res.rows.forEach(item=>{
        const result = parseMultipolygon(item.geom).slice(0, -1);
        window.graphicDefect.addGraphic({
          id:item.defectId,
          name:item.roadName,
          positions:result,
          type: "polygon",
          attr:{...item},
          style: {
              color: item.repairStatus=="无需维修"?'#409EFF':item.repairStatus=="待维修"?'#d9001b':item.repairStatus=="已派单"?'#E6A23C':'#529b2e',
              outline: true,
              opacity: 0.3,
              outlineColor: item.repairStatus=="无需维修"?'#409EFF':item.repairStatus=="待维修"?'#d9001b':item.repairStatus=="已派单"?'#E6A23C':'#529b2e',
              outlineWidth: 2.0,
              edittype:"polygon",
              label: {
                text: item.defectType,
                color: '#fff',
                outline:true,
                outlineColor: "#000",
                outlineWidth:4,
                setHeight:5,
                scaleByDistance:true,
              }
          }
        })
      })
    }
  })
}

const getListInfo = async () => {
  await getDefectList(queryParams.value).then(res=>{
    if(res.code === 200) {
      tableData.value = res.rows
      queryParams.value.total = res.total
    }
  })
}

window.getListInfo = getListInfo

const flyToGraphic = (data) => {
  window.map.flyToGraphic(window.graphicDefect.getGraphicById(data.defectId),{radius:100})
  showAll.value = false
}

const getExcel = () => {

  let data = {
    ...queryParams.value,
    userId: user.userId
  }
  
  if(user.roles.includes('superadmin')){
    data = {
      ...queryParams.value,
      userId: ''
    }
  }else{
    data = {
     ...queryParams.value,
      userId: user.userId
    }
  }

  // 生成默认文件名：道路缺陷_当前日期
  const defaultFileName = `${queryParams.value.roadName}${queryParams.value.stakeNumber}道路缺陷_${new Date().toISOString().split('T')[0]}`
  
  ElMessageBox.prompt('请输入导出文件名', '导出确认', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    inputValue: defaultFileName,
    inputPattern: /^[\u4e00-\u9fa5a-zA-Z0-9_-]+$/,
    inputErrorMessage: '文件名只能包含中文、英文、数字、下划线和横线',
    beforeClose: (action, instance, done) => {
      if (action === 'confirm') {
        const fileName = instance.inputValue.trim()
        if (!fileName) {
          ElMessage.warning('文件名不能为空')
          return
        }
        ElMessageBox.confirm('是否确认导出该文件？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          downloade.getDefectExcel({
            ...data,
            fileName: fileName
          })
          done()
        }).catch(() => {
          // 用户取消导出
        })
      } else {
        done()
      }
    }
  }).catch(() => {
    // 用户取消输入文件名
  })
}

const endDraw = async () => {
  tabShow.value = false
  // 释放键盘监听事件
  document.removeEventListener('keydown', handleKeyDown)
  const points = window.endDraw()
  const graphic = new mars3d.graphic.PolygonEntity({
    positions: [...points], // Pass a copy of the positions array
    style: {
      color: '#d9001b',
      opacity: 0.3,
      outline: true,
      outlineColor: '#d9001b',
      outlineWidth: 2.0,
      label: {
        text: "道路缺陷",
        color: '#fff',
        outline: true,
        outlineColor: "#000",
        outlineWidth: 4,
        setHeight: 5,
        scaleByDistance: true,
      }
    },
    attr: {
      category: '其他',
      remark: '',
    }
  });
  window.graphicDefect.addGraphic(graphic);
  const loadingInstance = ElLoading.service({
    lock: true,
    text: '正在分析图形，请稍后',
    background: 'rgba(0, 0, 0, 0.7)',
  })
  
  try {
    const degreesPositions = [...points,points[0]].map(cartesian => {
      const cartographic = Cesium.Cartographic.fromCartesian(cartesian)
      return [
        Cesium.Math.toDegrees(cartographic.longitude),
        Cesium.Math.toDegrees(cartographic.latitude),
        cartographic.height
      ]
    })

    const coordinates = degreesPositions.map(pos => `${pos[0]} ${pos[1]}`).join(',')
    const wkt = `MULTIPOLYGON(((${coordinates})))`
    
    const res = await isPointInBetweenStations({'geometry': wkt})
    if (res.code === 200) {
      if (res.data != null) {
        graphic.attr = {
          stakeNumber: res.data.pileNum,
          roadName: res.data.roadName,
        }
        window.graphicDefect.startEditing(graphic)
      } else {
        window.graphicDefect.removeGraphic(graphic)
        ElMessage.error('该图形不在道路上，请重新绘制!')
      }
    }
  } catch (error) {
    console.error('Error in startDraw:', error)
    ElMessage.error('绘制过程出错，请重试!')
    window.graphicDefect.removeGraphic(graphic)
  } finally {
    loadingInstance.close()
  }
}
const stepBack = () => {
  window.undoLastPoint()
}

/** 搜索用户列表 */
const handleUserSearch = async (query: string, cb) => {
  const res = await getUserList(query);
  cb(res.rows);
};

/** 选择用户 */
const handleUserSelect = (item: { userName: string; userId: number }) => {
  queryParams.value.userName = item.userName;
  queryParams.value.userId = item.userId;
};

const showList = () => {
  store.openStatistics()
}

const clearUser = () => {
  if (user.roles.includes('superadmin')) {
    queryParams.value.userName = '';
    queryParams.value.userId = '';
  }else {
    queryParams.value.userId = user.userId;
  }
}

onMounted(async()=>{
  // 等待用户信息加载完成
  if (!user.userId) {
    await new Promise(resolve => {
      const unwatch = watch(() => user.userId, (newVal) => {
        if (newVal) {
          unwatch()
          resolve(true)
        }
      }, { immediate: true })
    })
  }
  if (user.roles.includes('superadmin')) {
    queryParams.value.userId = ''
  }else{
    queryParams.value.userId = user.userId
  }
  await getList()
})
</script>

<template>
<div :class="!store.isOpenTabel?'roadInfoBox':showAll?'roadInfoBox show showAll':'roadInfoBox show'">
  <div class="content-wrapper">
    <div class="cardBox">
      <el-card shadow="hover" style="background: transparent;">
        <el-form ref="queryFormRef" :model="queryParams" :inline="true">
          <el-form-item label="人员名称" prop="roadName" v-if="user.roles.includes('superadmin')">
            <el-autocomplete
              v-model="queryParams.userName"
              :fetch-suggestions="handleUserSearch"
              placeholder="请输入分发账号名称"
              clearable
              @clear="clearUser"
              @select="handleUserSelect"
              style="width: 100%"
            >
              <template #default="{ item }">
                <div class="value">{{ item.userName }}</div>
              </template>
            </el-autocomplete>
          </el-form-item>
          <el-form-item label="道路名称" prop="roadName">
            <el-input v-model="queryParams.roadName" placeholder="请输入道路名称" clearable @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="桩号范围" prop="stakeNumber">
            <el-input v-model="queryParams.stakeNumber" placeholder="请输入桩号范围" clearable @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="缺陷等级" prop="dataName">
            <el-select v-model="queryParams.defectLevel" filterable clearable placeholder="请选择缺陷等级">
              <el-option v-for="item in dataNameList" :key="item" :label="item" :value="item"> </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="维修状态" prop="dataName">
            <el-select v-model="queryParams.repairStatus" filterable clearable placeholder="请选择维修状态">
              <el-option v-for="item in repairStatusList" :key="item" :label="item" :value="item"> </el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <div>
              <el-button type="primary" :icon="Search" @click="getList">搜索</el-button>
              <el-button :icon="Refresh" @click="resetQuery">重置</el-button>
              <!-- <el-button type="warning" :icon="EditPen" @click="startDraw">绘制缺陷</el-button> -->
              <el-button type="warning" :icon="EditPen" @click="startDraw" v-if="!user.roles.includes('superadmin')">绘制缺陷</el-button>
              <el-button type="success" :icon="TrendCharts" @click="showList" v-else>分类统计</el-button>
              <!-- <el-button type="success" :icon="TrendCharts" @click="showList">分类统计</el-button> -->
              <el-button type="info" :icon="FolderOpened" @click="getExcel">导出表格</el-button>
            </div>
            <div>
              <el-button type="danger" :icon="CloseBold" @click="closeTab">关闭</el-button>
            </div>
          </el-form-item>
        </el-form>
      </el-card>
    </div>
    <div class="table-container">
      <div class="transparent-table">
        <el-table :data="tableData" style="width: 100%" :row-style="getRowStyle" :header-cell-style="{ background: 'transparent', color: 'white', textAlign: 'center'}" :cell-style="{ textAlign: 'center' }">
          <el-table-column prop="roadName" label="道路名称" width="80" />
          <el-table-column prop="stakeNumber" label="桩号" width="120" >
            <template #default="scope">
              <div style="cursor: pointer;" @dblclick="flyToGraphic(scope.row)">{{ scope.row.stakeNumber }}</div>
            </template>
          </el-table-column>
          <el-table-column prop="direction" label="行向" width="60" />
          <el-table-column prop="defectType" label="缺陷类型" />
          <el-table-column prop="defectLevel" label="缺陷等级" width="80" />
          <el-table-column prop="defectTime" label="时间" width="110" />
          <el-table-column prop="defectArea" label="缺陷面积/㎡" width="110" />
          <el-table-column prop="computeFormula" label="计算式" width="100" />
          <el-table-column prop="distance" label="位置距离" width="180">
            <template #default="scope">
              距离{{ scope.row.closeStakeNumber }}，{{ scope.row.distance }}米
            </template>
          </el-table-column>
          <el-table-column prop="repairStatus" label="维修状态" width="80" />
          <!-- <el-table-column v-show="!showAll" label="操作" align="center" class-name="small-padding fixed-width" width="60" fixed="right">
            <template #default="scope">
                  <div style="cursor: pointer;"><img @click.stop="flyToGraphic(scope.row)" style="width: 16px; margin-left: 5px;" src="@/assets/image/dingwei.png" alt=""></div>
            </template>
          </el-table-column> -->
        </el-table>
      </div>
      <div class="paginationBox">
            <el-pagination
              v-model:current-page="queryParams.pageNum"
              v-model:page-size="queryParams.pageSize"
              :page-sizes="[10, 20, 50, 100]"
              layout="total, sizes, prev, pager, next"
              :total="queryParams.total"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
      </div>
    </div>
    <div class="showAllBrn" @click="showAll=!showAll">
      <div class="arrow">
        <div class="arrow-top"></div>
        <div class="arrow-bottom"></div>
      </div>
    </div>
  </div>


</div>

<div class="drawBtn" v-show="tabShow">
  <el-button type="success" :icon="RefreshLeft" @click="stepBack">撤销</el-button>
  <el-button type="primary" @click="endDraw()">结束绘制</el-button>
</div>
</template>

<style scoped>
.roadInfoBox {
  position: fixed;
  left: -100%;
  top: 0;
  width: 500px;
  height: 100vh;
  background: rgba(19, 32, 57, 0.9);
  transition: all .8s cubic-bezier(0.68, -0.55, 0.265, 1.55);
  padding: 10px;
  z-index: 99;
  color: #fff;
  box-shadow: 0 0 30px rgba(0, 0, 0, 0.5);
  font-family: "思源黑体", "Roboto", sans-serif;
}

.content-wrapper {
  height: calc(100% - 30px);
  display: flex;
  flex-direction: column;
}

.roadInfoBox.show {
  left: 0;
}

.showAll {
  width: 1000px;
}

.cardBox {
  position: relative;
  flex-shrink: 0;
}

.table-container {
  position: relative;
  flex: 1;
  display: flex;
  flex-direction: column;
  min-height: 0;
  margin-top: 10px;
}

.transparent-table {
  flex: 1;
  overflow: auto;
}

.roadInfoBox .cardBox ::v-deep label {
  color: white;
}

.roadInfoBox .cardBox ::v-deep .el-form {
  display: flex;
  justify-content: space-between;
  flex-wrap: wrap;
  gap: 10px;
}

.roadInfoBox .cardBox ::v-deep .el-form--inline .el-form-item {
  margin: 0;
  width: calc(50% - 10px); 
}
.roadInfoBox .cardBox ::v-deep .el-form--inline .el-form-item .el-input {
  width: 100%;
}

.roadInfoBox .cardBox ::v-deep .el-form--inline .el-form-item:last-child {
  margin: 0;
  width: 100%; 
}

.roadInfoBox .cardBox ::v-deep .el-form--inline .el-form-item:last-child .el-form-item__content{
  display: flex;
  justify-content: space-between;
}

.roadInfoBox .cardBox ::v-deep .el-select,
.roadInfoBox .cardBox ::v-deep .el-select .el-input{
  width: 100%;
}

/* 下拉框样式覆盖 */
.roadInfoBox ::v-deep .el-select .el-input__wrapper,
.roadInfoBox ::v-deep .el-select .el-select__wrapper {
  background: var(--panel-background) !important;
  box-shadow: 0 0 0 1px rgba(255, 255, 255, 0.2) inset !important;
  border-radius: 4px;
  color: #fff;
}

.roadInfoBox ::v-deep .el-select .el-input__wrapper.is-focus {
  box-shadow: 0 0 0 1px var(--secondary-color) inset !important;
}

.roadInfoBox ::v-deep .el-select .el-input__inner {
  color: #fff !important;
}

.roadInfoBox ::v-deep .el-select .el-input__suffix {
  color: #fff !important;
}

.transparent-table ::v-deep .el-table {
  background: transparent !important;
  color: white;
  height: 100%;
}

.transparent-table ::v-deep .el-table th,
.transparent-table ::v-deep .el-table td {
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
}

.transparent-table ::v-deep .el-table__empty-block {
}

.paginationBox {
  flex-shrink: 0;
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.paginationBox ::v-deep .el-pagination .el-pager li,
.paginationBox ::v-deep .el-pagination button,
.paginationBox ::v-deep .el-select .el-input__wrapper,
.paginationBox ::v-deep .el-pagination .el-input__inner,
.paginationBox ::v-deep .el-pagination__total {
  background: transparent;
  color: white;
}

.paginationBox ::v-deep .el-pagination .el-pager li.is-active {
  background-color: #005BAA !important;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.2);
}

.drawBtn {
  position: fixed;
  bottom: 50px;
  left: 50%;
  transform: translateX(-50%);
  display: flex;
  align-items: center;
  z-index: 999;
  gap: 10px;
}

.roadInfoBox ::v-deep .el-button {
  background-color: var(--app-background);
  padding: 8px 10px;
}
.roadInfoBox ::v-deep .el-button+.el-button {
  margin-left: 10px;
}

.roadInfoBox ::v-deep .el-card {
  background: rgba(19, 32, 57, 0.7);
  border: none;
  border-radius: 10px;
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.15);
  transition: all 0.3s ease;
}
</style>

<style scoped>
.showAllBrn {
  position: absolute;
  right: 0;
  top: 50%;
  transform: translateY(-50%);
  cursor: pointer;
  transition: all .8s cubic-bezier(0.68, -0.55, 0.265, 1.55);
}

.showAll .showAllBrn {
  transform: translateY(-50%) rotate(180deg);
}
/* From Uiverse.io by Nawsome */ 
.arrow {
  cursor: pointer;
  height: 60px;
  left: 50%;
  position: absolute;
  top: 50%;
  transform: translateX(-50%) translateY(-50%);
  transition: transform 0.1s;
  width: 50px;
}

.arrow-top, .arrow-bottom {
  background-color: #666;
  height: 4px;
  left: -5px;
  position: absolute;
  top: 50%;
  width: 100%;
}

.arrow-top:after, .arrow-bottom:after {
  background-color: #fff;
  content: "";
  height: 100%;
  position: absolute;
  top: 0;
  transition: all 0.15s;
}

.arrow-top {
  transform: rotate(45deg);
  transform-origin: bottom right;
}

.arrow-top:after {
  left: 100%;
  right: 0;
  transition-delay: 0s;
}

.arrow-bottom {
  transform: rotate(-45deg);
  transform-origin: top right;
}

.arrow-bottom:after {
  left: 0;
  right: 100%;
  transition-delay: 0.15s;
}
.arrow:active {
  transform: translateX(-50%) translateY(-50%) scale(0.9);
}
</style>
